// https://leetcode.cn/problems/print-foobar-alternately/
// Created by ade on 2022/11/2.
// 两个线程A和B，分别交替打印foo和bar
#include <semaphore.h>
class FooBar {
private:
    int n;
    sem_t foo_ok, bar_ok;

public:
    FooBar(int n) {
        this->n = n;
        sem_init(&foo_ok, 0, 1);
        sem_init(&bar_ok, 0, 0);
    }

    void foo(function<void()> printFoo) {
        for (int i = 0; i < n; i++) {
            sem_wait(&foo_ok);
            // printFoo() outputs "foo". Do not change or remove this line.
            printFoo();
            sem_post(&bar_ok);
        }
    }

    void bar(function<void()> printBar) {
        for (int i = 0; i < n; i++) {
            sem_wait(&bar_ok);
            // printBar() outputs "bar". Do not change or remove this line.
            printBar();
            sem_post(&foo_ok);
        }
    }
};